package com.yanqu.road.reids.subpub;

import com.yanqu.road.logic.redis.RedisManger;
import com.yanqu.road.server.TempMgr;

public class RedisSubPubRunner implements Runnable {

    static volatile int count = 0;

    final RedisReliableMessageSubPub pubSub;

    public static boolean stop = false;

    public RedisSubPubRunner(RedisReliableMessageSubPub pubSub) {
        if(count > 0){
            throw new RuntimeException("重复注册");
        }
        count++;
        this.pubSub = pubSub;
    }

    @Override
    public void run() {

        while (true){

            if(stop){
                break;
            }

            //TempMgr.getLogger().info("当前线程：{}", Thread.currentThread().toString());
            try {
                String[] channelList = new String[RedisReliableMessageSubPub.getList().size()];
                int i = 0;
                for (ReliableMessageSubPub subPub : RedisReliableMessageSubPub.getList()) {
                    channelList[i++] = subPub.getChannel();
                }
                //此位置阻塞
                RedisManger.getRedisUtil().subscribe(pubSub, channelList);
            }catch (Exception e){
                TempMgr.getLogger().error("", e);
            }finally {
                try {
                    //TempMgr.getLogger().info("当前线程：{}", Thread.currentThread().toString());
                    //有异常，1分钟后重试
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }

        }

    }

    public static void setStop(boolean stop) {
        RedisSubPubRunner.stop = stop;
    }
}
